package com.avira.smstest;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.telephony.SmsMessage;
import android.util.Log;

public class SMSReceiver extends BroadcastReceiver 
{
    private static volatile int notificationID = 0; 
	
    public void onReceive(Context context, Intent intent)
    {
        Bundle bundle = intent.getExtras();
        try
        {
            if (bundle != null)
            { 
                Object[] pdusObj = (Object[]) bundle.get("pdus");
                
                for (int i = 0; i < pdusObj.length; i++)
                {
                    SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                    String sender = currentMessage.getDisplayOriginatingAddress();
                    String contents = currentMessage.getDisplayMessageBody();
                    long timestamp = currentMessage.getTimestampMillis();
                    
                    SMSObject smsObject = new SMSObject(sender, contents, timestamp);

                    Log.i("SmsReceiver", "senderNum: "+ sender + ", message: " + contents + ", date: " + smsObject.getDate() + ", " + smsObject.getHour() );
                    
                    //don't delete right after it has been received(should add some kind of delay here if done this way) - it does not exist on the physical media yet!
                    //deleteSMS(context, contents, sender);
                    
                    //instead of deleting, abort the broadcast and stop the sms from being saved- this only works if you add a high enough priority to the receiver
                    abortBroadcast();
                    
                    Log.i("SmsReceiver", "SMS deleted");
                    
                    showNotification(context, smsObject);
                }
            }
        }
        catch (Exception e)
        {
            Log.e("SmsReceiver", "Exception smsReceiver" + e);
        }
    }
    
    private void deleteSMS(Context context, String contents, String sender)
    {
        Uri uriSms = Uri.parse("content://sms/inbox");
        Cursor cursor = context.getContentResolver().query(uriSms,
					            					new String[] {"_id", "thread_id", "address", "person", "date", "body"}, 
					            					null, 
					            					null, 
					            					null);

        if (cursor != null && cursor.moveToFirst() )
        {
            do
            {
                long id = cursor.getLong(0);
                String address = cursor.getString(2);
                String body = cursor.getString(5);

                if (contents.equals(body) && address.equals(sender) )
                {
                    context.getContentResolver().delete(Uri.parse("content://sms/" + id), null, null);
                    break;
                }
            } 
            while (cursor.moveToNext() );
        }
    }
    
    private void showNotification(Context context, SMSObject smsObject)
    {
        Intent intent = new Intent(context, MainActivity.class);
    	//pass to another activity for further processing
        intent.putExtra(SMSObject.class.getCanonicalName(), smsObject);

        //must have PendingIntent.FLAG_UPDATE_CURRENT and unique id, otherwise on multiple notifications the extra data would get corrupted
        PendingIntent contentIntent = PendingIntent.getActivity(context, notificationID, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
											        .setSmallIcon(R.drawable.ic_launcher)
											        .setContentTitle(smsObject.getSender() )
											        .setContentText(smsObject.getDate() + ", " + smsObject.getHour() );
		mBuilder.setContentIntent(contentIntent);
		mBuilder.setAutoCancel(true);
		NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		mNotificationManager.notify( notificationID++, mBuilder.build() );
    }  
    
}